<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="title" @ok="handleSubmit" :width="750" :minHeight="200" destroyOnClose>
    <Tabs v-model:activeKey="state.channelType" :tabBarGutter="10" :class="`${prefixCls}-tab`" @change="handleTabChange" v-if="!state.isClickChannel">
      <template v-for="item in state.channelList" :key="item.channelType">
        <TabPane :tab="item.name" forceRender />
      </template>
    </Tabs>

    <BasicForm @register="registerForm" @value-change="handleFormChange">
      <template #contentEdit="{ model, field }">
        <!-- <RenderHtml v-else :renderHtml="false" :text="model[field]" height="130px" :fullScreen="true" :zIndex="20000" /> -->
        <InputTextArea v-model:value="model[field]" :readOnly="!useIam().isAppHubOrMgt()" :autoSize=" { minRows: 2, maxRows: 8 }"/>
      </template>
    </BasicForm>

    <Divider v-if="!state.loading && state.channelInfo?.customFlag">模板字段配置</Divider>
    <Alert v-if="state.channelInfo?.customFlag" banner closable style="margin-bottom: 10px" type="info">
      <template #description>
        <span v-for="(item, index) in state.fieldSettingTips" :key="index"> {{ index + 1 }}. {{ item }} <br /></span>
      </template>
    </Alert>
    <JVxeTable
      v-if="!state.loading && state.channelInfo?.customFlag"
      ref="tableRef"
      stripe
      keepSource
      rowSelection
      sortKey="sortNo"
      rowKey="msgField"
      :auto-resize="true"
      :sync-resize="state.activeKey"
      :maxHeight="600"
      :disabledRows="{ isPk: [true] }"
      :loading="state.loading"
      :disabled="state.disabled"
      :columns="state.columns"
      :dataSource="state.dataSource"
      v-bind="vuxTableProps"
      @select-row-change="handleSelectdRow"
    >
      <template #toolbarAfter> </template>
    </JVxeTable>

    <!-- 底部展示仅保存、保存并关闭 -->
    <template #footer>
      <a-button @click="handleSubmit(false)" type="primary" :loading="state.saveLoading" ghost>仅保存</a-button>
      <a-button @click="handleSubmit(true)" type="primary" :loading="state.saveLoading">保存并关闭</a-button>
    </template>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, nextTick, reactive, onMounted } from "vue"
  import { BasicModal, useModalInner } from "/@/components/Modal"
  import { BasicForm, useForm } from "/@/components/Form/index"
  import { channelConfigSchema } from "../data"
  import { saveNoticeChannel, getNoticeChannel } from "../api"
  import { useMessage } from "/@/hooks/web/useMessage"
  import { Tabs, Alert, Input } from "ant-design-vue"
  import { JVxeTypes, JVxeColumn } from "/@/components/jeecg/JVxeTable/types"
  import { Divider } from "ant-design-vue"
  import { VxeGridProps } from "vxe-table"
  import { useDesign } from "/@/hooks/web/useDesign"
  import { isHtml } from "/@/utils/common/htmlUtil"
  import { useUserStore } from "/@/store/modules/user"
  import { isNullOrUnDef } from "/@/utils/is"
  import { ChannelTypeEnum } from "../model"
  import { useIam } from '/@/hooks/web/useIam'

  const InputTextArea = Input.TextArea
  const { prefixCls } = useDesign("config-channel")

  const TabPane = Tabs.TabPane

  const { createMessage } = useMessage()

  const emit = defineEmits(["register", "success"])

  const vuxTableProps = ref<VxeGridProps<any>>({
    editConfig: {
      trigger: "click",
      beforeEditMethod: ({ row, rowIndex, column, columnIndex }) => {
        // 如果消息字段中设置了不可编辑字段的模板消息内容, 则禁用
        if (column.params.key === "value" && !row.editTpl) {
          createMessage.warn("所选字段的模板内容不可编辑")
          return false
        }

        return true
      },
    },
    checkboxConfig: {
      range: true,
      checkAll: false,
      // 默认勾选指定行（只会在初始化时被触发一次，需要有 row-config.keyField）
      // 这里为了使在设置初始化选中的行, 需要先不让视图渲染, 所以要设置 成v-if = false, 因为vux-table只会执行一次
      // 当初始化选中中行后再设置成true
      checkRowKeys: [],
      // 用于禁止某一行
      checkMethod: ({ row }) => {
        return true
      },
    },
  })

  const tableRef = ref()
  const msgFieldType = JVxeTypes.input
  const vxeColumns = ref<JVxeColumn[]>([])
  const [registerForm, { resetFields, setFieldsValue, validate, setProps }] = useForm({
    labelWidth: 90,
    schemas: channelConfigSchema,
    showActionButtonGroup: false,
    wrapperCol: {
      xs: { span: 23 },
      sm: { span: 22 },
    },
  })

  const state = reactive<any>({
    loading: true,
    saveLoading: false,
    width: 750,
    channelType: "",
    channelInfo: undefined,
    // 是否点击渠道
    isClickChannel: false,
    record: {},
    // 是否可以编辑模板内容
    showEdit: false,
    labelCol: {},
    channelList: [],
    fieldSettingTips: [
      "推送的第三方模板(微信小程序/微信公众号)里有的字段才勾选，如果没有请勿勾选。",
      "这里的模板字段对应到第三方渠道消息中的模板字段",
      "只有勾选某一行, 修改模板字段名才会生效",
      // '以 sl_ 开头的模板字段名, 会将值转成短链(short link)',
    ],

    // 模板字段配置
    columns: vxeColumns,
    // 模板字段数据
    dataSource: [],
    isUpdate: false,
    disabled: false,
  })

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    try {
      console.log('data', data)
      await resetFields()
      state.loading = true
      setModalProps({ confirmLoading: false, loading: true })
    
      state.record = data.record
      state.isClickChannel = !!data.selectedChannel
      state.channelList = data.record.channelList
      state.channelType = data.selectedChannel?.channelType || state.channelList[0].channelType
      state.channelInfo = data.selectedChannel || state.channelList[0]
      state.isUpdate = !!state.channelInfo.id
      // state.showEdit = data.showEdit
      state.disabled = !useIam().isAppHubOrMgt()

      // setVxeColumns(state.disabled ? JVxeTypes.normal : JVxeTypes.input)
      setVxeColumns(JVxeTypes.input)

      state.dataSource = (data.record.msgFields || []).map((e) => ({
        msgField: e.key,
        desc: e.desc, // 描述
        key: e.key, // 模板的字段(默认和消息字段一样, 不过可以单独指定)
        editTpl: e.editTpl,
      }))
      console.log("record", state.record)
      if (state.channelType != ChannelTypeEnum.PC && state.channelType != ChannelTypeEnum.WX_MA ) {
        setProps({ labelWidth: 100 })
      }

      await initChannelSetting(state.channelInfo)
      setModalProps({ loading: false })

      await setFieldsValue({
        channelType: state.channelType,
      })
    } catch (e) {
      createMessage.error(`未知异常 [${e}]`)
    } finally {
      setModalProps({ loading: false })
      state.loading = false
    }
  })

  const title = computed(() => {
    return state.isClickChannel ? `配置 ${state.record.name}-${state.channelInfo.name} 渠道` : `编辑 ${state.record.name} 渠道`
  })

  const setVxeColumns = (msgFieldType = JVxeTypes.input) => {
    vxeColumns.value = [
      {
        title: "字段名称",
        key: "desc",
        width: 150,
        validateRules: [{ required: true, message: "${title}不能为空" }],
      },
      {
        title: "消息字段",
        key: "msgField",
        type: JVxeTypes.normal,
        width: 150,
        titleHelp: { message: "推送消息时传递的字段名" },
      },
      {
        title: "模板字段",
        key: "key",
        type: msgFieldType,
        width: 150,
        titleHelp: { message: "第三方模板中的字段名" },
        validateRules: [{ required: true, message: "${title}不能为空" }],
      },
      {
        title: "模板内容",
        key: "value",
        type: JVxeTypes.input,
        defaultValue: "",
        align: "center",
      },
    ]
  }

  const handleSelectdRow = (rows) => {
    // tableRef.value.gridRef.setCheckboxRow(state.dataSource[0], true)
    console.log("rowsKey: ", rows.selectedRows)
  }

const handleFormChange = async (value) => {
    state.channelInfo = { ...state.channelInfo, ...value }
  }

  const handleTabChange = async (channelType) => {
    await resetFields()
    tableRef.value?.gridRef?.clearCheckboxRow()
    console.log("channelType", channelType)
    state.channelType = channelType
    state.channelInfo = state.channelList.filter((e) => e.channelType === channelType)[0]
    state.isUpdate = !!state.channelInfo?.id
    await initChannelSetting(state.channelInfo)
    setFieldsValue({ channelType })
  }

  const initChannelSetting = async (channelInfo) => {
    state.loading = true
    setModalProps({ loading: true })
    try {
      const channelData = await getNoticeChannel({ 
        noticeId: channelInfo.noticeId, 
        channelType: channelInfo.channelType 
      })
      state.channelInfo  = channelData
      if (!channelData) {
        return
      }

      const selectedRowKeys: any[] = Object.keys(channelData.settings?.tplField)
      console.log("selectedRowKeys", selectedRowKeys)

      // @ts-ignore
      const checkRowKeys = vuxTableProps.value?.checkboxConfig?.checkRowKeys
      console.log('checkRowKeys', checkRowKeys, selectedRowKeys)
      checkRowKeys?.splice(0, checkRowKeys.length)
      checkRowKeys?.push(...selectedRowKeys)
      
      state.dataSource = state.dataSource.map((e) => {
        const tplField = channelData.settings?.tplField[e.msgField]
        return {
          ...e,
          value: tplField?.value,
          key: tplField?.key || e.key,
        }
      })
      
      const settings = channelData.settings
      for (const key in settings) {
        if (isNullOrUnDef(settings[key])) {
          delete settings[key]
        }
      }
      // 如果是应用管理端则强制设置为非自定义
      // 这里为了方便处理, 应用管理端也设置成自定义(保存时候在强制设置成非自定义)
      let customFlag = useIam().isAppHubOrMgt() || channelData.customFlag
      channelData.customFlag = customFlag
      await setFieldsValue({
        ...settings,
        status: channelData.status,
        channelType: state.channelType,
        customFlag
      })

    } catch (e) {
      console.error(e)
    } finally {
      let time = setTimeout(() => {
        setModalProps({ loading: false })
        clearTimeout(time)
      }, 200)
      state.loading = false
    }
  }

  async function handleSubmit(isClose) {
    state.saveLoading = true
    try {
      let values = await validate()
      const tplField = {}
      tableRef.value?.getSelectedData()?.forEach((e) => {
        tplField[e.msgField] = {
          key: e.key,
          desc: e.desc,
          value: e.value,
        }
      })
      const reqParams = {
        settings: {
          tplField,
          ...values,
        },
        id: state.channelInfo?.id,
        noticeId: state.record.id,
        channelType: state.channelType,
        status: values.status,
        customFlag: !useIam().isAppHubOrMgt() && state.channelInfo?.customFlag
      }

      console.log("reqParams", reqParams)
      console.log("channelInfo", state.channelInfo)
      setModalProps({ confirmLoading: true })
      await saveNoticeChannel(reqParams)
      if (isClose) {
        closeModal()
        emit("success")
      }
      createMessage.success(`配置【${state.channelInfo.name}】成功`)
    } catch (e) {
      console.error("error", e)
    } finally {
      state.saveLoading = false
      setModalProps({ confirmLoading: false })
    }
  }
</script>

<style lang="less">
  @prefix-cls: ~"@{namespace}-config-channel";

  .@{prefix-cls} {
    &-tab {
      margin-bottom: -15px !important;
    }
  }
</style>
